/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
 *
 */

import path from 'path';

import { Input, OutputFile } from '@ohos/hvigor';
import fse from 'fs-extra';

import { TaskNames } from '../common/task-names.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { OhosHapTask } from '../task/ohos-hap-task.js';
import { getOhosUiTransformOptimization } from './ohos-uitransform-optimization.js';

export const MODULE_INFO_CODE = `
//@ts-noCheck
export const __MODULE_NAME__: string = __getCurrentModuleName__()
export const __BUNDLE_NAME__: string = __getCurrentBundleName__()
`;

/**
 * 要在generated目录生成一个ModuleInfo.ts文件，用于后续操作
 * 该任务的主要逻辑就是生成ModuleInfo.ts文件，并写入MODULE_INFO_CODE内容
 * 此任务主要用于hap/hsp模块，CreateHarModuleInfo任务主要用于处理har模块
 */
export class CreateModuleInfo extends OhosHapTask {
  @OutputFile({ isDirectory: false }) private readonly outputFile: string;

  constructor(taskService: TargetTaskService) {
    super(taskService, TaskNames.CommonTask.CREATE_MODULE_INFO);
    this.outputFile = this.pathInfo.getGenerateModuleInfoPath();
  }

  protected beforeTask(): void {
    if (fse.existsSync(this.outputFile)) {
      fse.removeSync(this.outputFile);
    }
  }

  @Input() private get ohosUiTransformOptimization(): boolean {
    return getOhosUiTransformOptimization(this.targetService);
  }

  taskShouldDo(): boolean {
    return getOhosUiTransformOptimization(this.targetService);
  }

  protected async doTaskAction() {
    fse.ensureDirSync(path.dirname(this.outputFile));
    fse.writeFileSync(this.outputFile, MODULE_INFO_CODE, { encoding: 'utf-8' });
  }

  initTaskDepends() {
    // empty
  }
}
